package com.rjwh.dingdong.client.thirdpartylogin;

import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;

import com.aishua.lib.utils.AsStrUtils;
import com.alibaba.fastjson.JSON;
import com.rjwh.dingdong.client.bean.localbean.XiaomiAccountBean;
import com.rjwh.dingdong.client.bean.localbean.XiaomiAccountBeanData;
import com.rjwh.dingdong.client.util.LogUtil;
import com.xiaomi.account.openauth.XMAuthericationException;
import com.xiaomi.account.openauth.XiaomiOAuthConstants;
import com.xiaomi.account.openauth.XiaomiOAuthFuture;
import com.xiaomi.account.openauth.XiaomiOAuthResults;
import com.xiaomi.account.openauth.XiaomiOAuthorize;

import java.io.IOException;

/**
 * 小米账号登录
 *
 * @author Kay
 * @ClassName XiaomiLoginManager
 * @Description
 * @date 2016-11-7
 * @history 2016-11-7 author: description:
 */

public class XiaomiLoginManager {
    private static final Long appId = 2882303761517511279L;
    private static final String redirectUri = "http://whtdlx.com";
    private static final String TAG = "XiaomiLoginManager";
    private final Context context;
    private AsyncTask waitResultTask;
    private AsyncTask showLoginResultTask;
    private OnXiaomiLoginListener onXiaomiLoginListener;
    private final XiaomiOAuthFuture<XiaomiOAuthResults> tokenfuture;

    public void setOnXiaomiLoginListener(OnXiaomiLoginListener onXiaomiLoginListener) {
        this.onXiaomiLoginListener = onXiaomiLoginListener;
    }

    public XiaomiLoginManager(Context context) {
        this.context = context;
        tokenfuture = new XiaomiOAuthorize()
                .setAppId(getAppId())
                .setRedirectUrl(getRedirectUri())
                .setScope(new int[]{XiaomiOAuthConstants.SCOPE_PROFILE})
                .startGetAccessToken((Activity) context);
    }

    public void doLogin() {
        waitAndShowFutureResult(tokenfuture);
    }

    private <V> void waitAndShowFutureResult(final XiaomiOAuthFuture<V> future) {
        waitResultTask = new AsyncTask<Void, Void, V>() {
            Exception e;

            @Override
            protected void onPreExecute() {
                showResult("waitAndShowFutureResult waiting for Future result...");
            }

            @Override
            protected V doInBackground(Void... params) {
                V v = null;
                try {
                    v = future.getResult();
                } catch (IOException e1) {
                    this.e = e1;
                } catch (OperationCanceledException e1) {
                    this.e = e1;
                } catch (XMAuthericationException e1) {
                    this.e = e1;
                }
                return v;
            }

            @Override
            protected void onPostExecute(V v) {
                if (v != null) {
                    if (v instanceof XiaomiOAuthResults) {
                        XiaomiOAuthResults results = (XiaomiOAuthResults) v;
                        if (!results.hasError()) {
                            String accessToken = results.getAccessToken();
                            String macKey = results.getMacKey();
                            String macAlgorithm = results.getMacAlgorithm();
                            if (!AsStrUtils.isEmpty(accessToken) && !AsStrUtils.isEmpty(macKey) && !AsStrUtils.isEmpty(macAlgorithm)) {
                                //获取token成功,并执行登录小米帐号
                                if (onXiaomiLoginListener != null) {
                                    onXiaomiLoginListener.onLoadingDailog();
                                }
                                XiaomiOAuthFuture<String> future = new XiaomiOAuthorize()
                                        .callOpenApi(context,
                                                getAppId(),
                                                XiaomiOAuthConstants.OPEN_API_PATH_PROFILE,
                                                accessToken,
                                                macKey,
                                                macAlgorithm);
                                showLoginResult(future);
                            }
                        }
                    }
                    showResult("waitAndShowFutureResult onPostExecute： " + v.toString());
                } else if (e != null) {
                    showResult("waitAndShowFutureResult Exception: "+e.toString());
                } else {
                    showResult("waitAndShowFutureResult done and ... get no result :(");
                }
            }
        }.execute();
    }

    private <V> void showLoginResult(final XiaomiOAuthFuture<V> future) {
        showLoginResultTask = new AsyncTask<Void, Void, V>() {
            Exception e;

            @Override
            protected void onPreExecute() {
                showResult("showLoginResult waiting for Future result...");
            }

            @Override
            protected V doInBackground(Void... params) {
                V v = null;
                try {
                    v = future.getResult();
                } catch (IOException e1) {
                    this.e = e1;
                } catch (OperationCanceledException e1) {
                    this.e = e1;
                } catch (XMAuthericationException e1) {
                    this.e = e1;
                }
                return v;
            }

            @Override
            protected void onPostExecute(V v) {
                if (onXiaomiLoginListener != null) {
                    onXiaomiLoginListener.onDismissDailog();
                }
                if (v != null) {
                    //获取小米帐号后登录app
                    LogUtil.e("showLoginResult ", "登录app");
                    try {
                        XiaomiAccountBean xiaomiAccountBean = JSON.parseObject(v.toString(), XiaomiAccountBean.class);
                        if (xiaomiAccountBean != null) {
                            XiaomiAccountBeanData data = xiaomiAccountBean.getData();
                            if (data != null) {
                                if (onXiaomiLoginListener != null) {
                                    onXiaomiLoginListener.onXiaomiLogin(data);
                                }
                            }
                        }
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }

                    showResult("showLoginResult onPostExecute: "+v.toString());
                } else if (e != null) {
                    showResult("showLoginResult Exception: "+e.toString());
                } else {
                    showResult("showLoginResult done and ... get no result :(");
                }
            }
        }.execute();
    }

    private void showResult(String text) {
        LogUtil.d(TAG, "result:" + text);
    }

    private static Long getAppId() {
        return appId;
    }

    private static String getRedirectUri() {
        return redirectUri;
    }

    public void onDestroy() {
        if (waitResultTask != null && !waitResultTask.isCancelled()) {
            waitResultTask.cancel(false);
        }
        if (showLoginResultTask != null && !showLoginResultTask.isCancelled()) {
            showLoginResultTask.cancel(false);
        }
    }
}
